package com.nulldev.util.security.hashing.MD5;

import java.security.MessageDigest;

import com.nulldev.util.JVM.JVM;
import com.nulldev.util.VariableAPI.StringsUtil;

public class MD5 {
	public static boolean isValidMD5(final String s) {
		return s.matches("[a-fA-F0-9]{32}");
	}

	public static boolean isValidSHA1(final String s) {
		return s.matches("[a-fA-F0-9]{40}");
	}

	public static byte[] getMD5(final byte[] input) {
		try {
			final MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(input);
			return md.digest();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public static String getMD5Hex(final byte[] input) {
		try {
			final MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(input);
			byte[] digest = md.digest();
			return getHex(digest);
		} catch (Exception e) {
			JVM.errorln(e);
			return null;
		}
	}

	public static String getMD5Hex_udz(final byte[] input) {
		try {
			final MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(input);
			byte[] byteData = md.digest();
			StringBuffer sb = new StringBuffer();
			for (int i = 0; i < byteData.length; i++) {
				sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
			}
			return sb.toString();
		} catch (Exception e) {
			JVM.errorln(e);
			return null;
		}
	}

	public static String getMD5Hex(final String[] inputStrings) {
		try {
			final MessageDigest md = MessageDigest.getInstance("MD5");
			for (final String i : inputStrings) {
				md.update(i.getBytes());
			}
			byte[] digest = md.digest();
			return getHex(digest);
		} catch (Exception e) {
			JVM.errorln(e);
			return StringsUtil.generateSecure(32);
		}
	}

	public static String getMD5Hex(final String inputString) {
		try {
			final MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(inputString.getBytes());
			byte[] digest = md.digest();
			return getHex(digest);
		} catch (Exception e) {
			JVM.errorln(e);
			return StringsUtil.generateSecure(32);
		}
	}

	public static String getMD5Hex_ASCII(final String inputString) {
		try {
			final MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(inputString.getBytes("US-ASCII"));
			byte[] digest = md.digest();
			return getHex(digest);
		} catch (Exception e) {
			JVM.errorln(e);
			return StringsUtil.generateSecure(32);
		}
	}

	private static final String HEXES = "0123456789abcdef";

	public static String getHex(byte[] raw) {
		final StringBuilder hex = new StringBuilder(2 * raw.length);
		for (final byte b : raw) {
			hex.append(HEXES.charAt((b & 0xF0) >> 4)).append(HEXES.charAt((b & 0x0F)));
		}
		return hex.toString();
	}
}
